package softtech.apps.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHandler extends SQLiteOpenHelper {

	private static final String LOG = DatabaseHandler.class.getName();
	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 37;

	// Database Name
	private static final String DATABASE_NAME = "AutoAnswerPhoneCall";

	private static final String TABLE_CONFIGS = "configs";

	// Contacts table name
	private static final String TABLE_CONTACTS = "contacts";

	private static final String TABLE_MESSAGES = "messages";

	private final String TABLE_RECORD = "records";

	private final String TABLE_TIMER = "timer";

	// Configs Table Column names
	private static final String CONFIG_KEY_ID = "id";
	private static final String CONFIG_KEY_VALUE = "value";
	private static final String CONFIG_KEY_WORD = "keyword";

	public String CFG_KW_DELETE_MSG_CHECK = "delmsgcheck";

	// Contacts Table Columns names
	private static final String KEY_ID = "id";
	private static final String KEY_NAME = "name";
	private static final String KEY_PH_NO = "phone_number";
	private static final String KEY_CONTACT_ID = "contact_id";
	private static final String KEY_CONTACT_TYPE = "type";

	/**
	 * Message Table Columns Names
	 */
	public static final String MSG_KEY_ID = "id";
	public static final String MSG_KEY_TITLE = "title";
	public static final String MSG_KEY_CONTENT = "content";
	public static final String MSG_KEY_DEFAULT = "is_default";
	public static final String MSG_KEY_DEFAULT_SYS = "has_default";

	/**
	 * Record Table Columns Names
	 */
	public static final String RECORD_ID = "id";
	public static final String RECORD_KEY = "keyword";
	public static final String RECORD_PATH = "path";
	public static final String RECORD_NAME = "name";

	public static final String RECORD_RAW_DEFAULT = "leave_message_please";
	/**
	 * Timer Table Columns Names
	 */
	private final String TIMER_ID = "id";
	private final String TIMER_NAME = "name";
	private final String TIMER_DATE = "date";
	private final String TIMER_TIME = "time";
	private final String TIMER_ISACTIVE = "is_active";
	private final String TIMER_REPEAT_WEEKLY = "repeat_weekly";

	// value default
	public final int VALUE_NON_DEFAULT = 0;

	public final int VALUE_IS_DEFAULT = 1;

	public String VALUE_TITLE_SMS_DEFAULT = "Unknown";

	public String VALUE_CONTENT_SMS_DEFAULT = "I'm busy now.";

	/**
	 * End
	 */

	Context myContext;

	private static String DB_PATH = "";

	private final String CREATE_CONFIGS_TABLE = "CREATE TABLE " + TABLE_CONFIGS
			+ "(" + CONFIG_KEY_ID + " INTEGER PRIMARY KEY," + CONFIG_KEY_VALUE
			+ " INTEGER," + CONFIG_KEY_WORD + " TEXT)";

	private final String CREATE_CONTACTS_TABLE = "CREATE TABLE "
			+ TABLE_CONTACTS + "(" + KEY_ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
			+ KEY_PH_NO + " TEXT," + KEY_CONTACT_ID + " TEXT,"
			+ KEY_CONTACT_TYPE + " INTEGER)";

	private final String CREATE_MESSAGES_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ TABLE_MESSAGES + "(" + MSG_KEY_ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT," + MSG_KEY_TITLE + " TEXT,"
			+ MSG_KEY_CONTENT + " TEXT," + MSG_KEY_DEFAULT + " INTEGER)";

	private final String CREATE_RECORD_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ TABLE_RECORD + "(" + RECORD_ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT," + RECORD_KEY + " TEXT,"
			+ RECORD_NAME + " TEXT," + RECORD_PATH + " TEXT)";

	private final String CREATE_TIMER_TABLE = "CREATE TABLE IF NOT EXISTS "
			+ TABLE_TIMER + "(" + TIMER_ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT," + TIMER_NAME + " TEXT,"
			+ TIMER_DATE + " TEXT," + TIMER_TIME + " TEXT,"
			+ TIMER_REPEAT_WEEKLY + " INTEGER DEFAULT 0," + TIMER_ISACTIVE
			+ " INTEGER DEFAULT 1)";

	public DatabaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.myContext = context;

		if (android.os.Build.VERSION.SDK_INT >= 4.2) {
			DB_PATH = myContext.getApplicationInfo().dataDir + "/databases/";
		} else {
			DB_PATH = "/data/data/" + myContext.getPackageName()
					+ "/databases/";
		}

		/*
		 * DB_PATH = Environment.getDataDirectory().getPath() + "/data/" +
		 * myContext.getPackageName() + "/databases/";
		 */
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

		// creating required tables
		db.execSQL(CREATE_CONFIGS_TABLE);
		db.execSQL(CREATE_CONTACTS_TABLE);
		db.execSQL(CREATE_MESSAGES_TABLE);
		db.execSQL(CREATE_RECORD_TABLE);
		db.execSQL(CREATE_TIMER_TABLE);
		// Init with table config
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(1,'enableapp')"); // enable
																		// app
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(1,'typetoreply')"); // type
																		// to
																		// reply
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(0,'synctodropbox')"); // sync
																			// to
																			// dropbox
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(0,'syncrange')"); // sync
																		// range
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(0,'contact')"); // contact
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(0,'isreceivevoicemessage')"); // receive
																					// voice
																					// message
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(3,'delaytime')"); // delay
																		// time
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(0,'delmsgcheck')");
		db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE
				+ "," + CONFIG_KEY_WORD + ") values(0,'delrrcheck')");
		/**
		 * value keyword 0 = enable app enableapp 1 = select reply type -> 0 =
		 * SMS, 1 = Reply by Record typetoreply 2 = mode sync -> 0 = manual sync
		 * ; 1 = auto sync synctodropbox 3 = sync range -> 0 = all calls ; 1 =
		 * favorites call syncrange 4 = option ignore -> 0 all contacts; 1 =
		 * contacts; 2 = unknown contact 5 = enable auto receive voice message
		 * -> 0 = disable; 1 = enable isreceivevoicemessage 6 = select delay
		 * time before accept call 3->10 sec delaytime 0 = uncheck -> 1 = check
		 * delmsgcheck 0 = uncheck -> 1 = check delrrcheck
		 * 
		 * */

		// Init with table contacts

		// Init with table messages
		// sms default
		db.execSQL("INSERT INTO "
				+ TABLE_MESSAGES
				+ "("
				+ MSG_KEY_TITLE
				+ ","
				+ MSG_KEY_CONTENT
				+ ","
				+ MSG_KEY_DEFAULT
				+ ") values('Sms Default','Im busy now. I will contact you as soon as possible. Thank you !',"
				+ VALUE_IS_DEFAULT + ")");

		// record default
		db.execSQL("INSERT INTO " + TABLE_RECORD + "(" + RECORD_KEY + ","
				+ RECORD_NAME + "," + RECORD_PATH
				+ ") values('defaultrecord','" + RECORD_RAW_DEFAULT
				+ "', 'raw')");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// on upgrade drop older tables
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONFIGS);
		// Drop older table if existed
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

		db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);

		db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECORD);

		db.execSQL("DROP TABLE IF EXISTS " + TABLE_TIMER);
		// create new tables
		onCreate(db);
	}

	/**
	 * Xu ly tat cac van de lien quan den config o day Them sua, xoa config Cac
	 * thong tin ve cau hinh duoc dat co dinh va khong the xoa, chi co the sua
	 * */

	// Update config
	public int updateConfig(Config config) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(CONFIG_KEY_VALUE, config.get_value());
		// updating row
		int temp = db.update(TABLE_CONFIGS, values, CONFIG_KEY_ID + " = ?",
				new String[] { String.valueOf(config.get_id()) });
		db.close();
		return temp;
	}

	// Select config
	public Config getConfig(int pos) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_CONFIGS, new String[] { CONFIG_KEY_ID,
				CONFIG_KEY_VALUE, CONFIG_KEY_WORD }, CONFIG_KEY_ID + "=?",
				new String[] { String.valueOf(pos) }, null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		Config config = new Config(Integer.parseInt(cursor.getString(0)),
				Integer.parseInt(cursor.getString(1)), cursor.getString(2));
		// return message
		db.close();
		return config;
	}

	/**
	 * Get config by keyword
	 * 
	 * @param keyword
	 *            containt value
	 * @return Config Object | null
	 */
	public Config getConfigByKeyWord(String keyword) {

		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_CONFIGS, new String[] { CONFIG_KEY_ID,
				CONFIG_KEY_VALUE, CONFIG_KEY_WORD }, CONFIG_KEY_WORD + "=?",
				new String[] { keyword }, null, null, null, " 1");
		if (cursor != null) {
			cursor.moveToFirst();

			Config config = new Config(Integer.parseInt(cursor.getString(0)),
					Integer.parseInt(cursor.getString(1)), cursor.getString(2));

			// return message
			db.close();
			return config;
		}

		return null;
	}

	/**
	 * insert config
	 * 
	 * @param cfg
	 *            want insert
	 * @return 0 if keyword of cfg exist else the row ID of the newly inserted
	 *         row
	 */

	public long insertConfig(Config cfg) {
		SQLiteDatabase db = this.getReadableDatabase();

		Config cfgInDb = getConfigByKeyWord(cfg.get_keyword());

		if (cfgInDb == null) {
			ContentValues values = new ContentValues();
			values.put(CONFIG_KEY_VALUE, cfg.get_value());
			values.put(CONFIG_KEY_WORD, cfg.get_keyword());
			long succes = db.insert(TABLE_CONFIGS, null, values);
			db.close();
			return succes;
		}

		return 0;
	}

	// Getting All config
	public List<Config> getAllConfigs() {

		// Log.d("CONFIG", "Bat dau truy van");

		List<Config> configList = new ArrayList<Config>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_CONFIGS;

		try {
			SQLiteDatabase db = this.getWritableDatabase();
			Cursor cursor = db.rawQuery(selectQuery, null);

			// looping through all rows and adding to list
			if (cursor.moveToFirst()) {
				do {
					Config config = new Config();
					config.set_id((Integer.parseInt(cursor.getString(0))));
					config.set_value(Integer.parseInt(cursor.getString(1)));
					config.set_keyword(cursor.getString(2));
					// Adding contact to list
					configList.add(config);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// return contact list
		return configList;
	}

	/**
	 * Xu ly contact o day. Bao gom cac thao tac them moi, sua, xoa, cap nhat
	 * contact
	 * 
	 * */

	// Adding new contact
	public void addContact(Contact contact) {
		SQLiteDatabase db = this.getWritableDatabase();

		// if(verification(contact.get_contact_id())==false){
		// Inserting Row
		// Log.d("FAILED",
		// "##########################Contact da duoc chen vao bang");
		ContentValues values = new ContentValues();
		values.put(KEY_NAME, contact.get_name()); // Contact Name
		values.put(KEY_PH_NO, contact.get_phone_number()); // Contact Phone
															// Number
		values.put(KEY_CONTACT_ID, contact.get_contact_id());
		values.put(KEY_CONTACT_TYPE, contact.get_type());
		db.insert(TABLE_CONTACTS, null, values);
		db.close(); // Closing database connection
		// }else{
		// Log.d("FAILED",
		// "##########################3Contact da ton tai trong table");
		// return;
		// }

	}

	public boolean verification(String _contact_id) throws SQLException {
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor c = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS + " WHERE "
				+ KEY_CONTACT_ID + "=" + _contact_id, null);
		if (c != null) {
			Log.d("EXIST", "Phone number nay da ton tai");
			return true; // return true if the value of _username already exists

		}

		return false; // Return false if _username doesn't match with any value
						// of the columns "Username"
	}

	// Getting single contact
	public Contact getContact(int id) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
				KEY_NAME, KEY_PH_NO, KEY_CONTACT_ID, KEY_CONTACT_TYPE }, KEY_ID
				+ "=?", new String[] { String.valueOf(id) }, null, null, null,
				null);
		if (cursor != null)
			cursor.moveToFirst();

		Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
				cursor.getString(2), cursor.getString(3),
				Integer.parseInt(cursor.getString(4)));
		// return contact
		db.close();
		return contact;
	}

	// Get contact by
	public Cursor getContactBy(String PhoneNumber) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
				KEY_NAME, KEY_PH_NO, KEY_CONTACT_ID, KEY_CONTACT_ID },
				KEY_PH_NO + "=?", new String[] { String.valueOf(PhoneNumber) },
				null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		// Contact contact = new Contact(cursor.getString(0),
		// cursor.getString(1), cursor.getString(2));
		// return contact
		return cursor;
	}

	// Check contact exist
	private boolean field_exists(String p_query) {
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor mCursor = db.rawQuery(p_query, null);
		if ((mCursor != null) && (mCursor.moveToFirst())) {
			mCursor.close();
			return true;
		}
		mCursor.close();
		return false;
	}

	// Getting All Contacts
	public List<Contact> getAllContacts() {
		List<Contact> contactList = new ArrayList<Contact>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Contact contact = new Contact(cursor.getString(0),
						cursor.getString(1), cursor.getString(2),
						cursor.getString(3), Integer.parseInt(cursor
								.getString(4)));
				// Adding contact to list
				contactList.add(contact);
			} while (cursor.moveToNext());
		}
		db.close();
		// return contact list
		return contactList;
	}

	// Getting All Contacts
	public List<Contact> getContactsByType(int type) {
		List<Contact> contactList = new ArrayList<Contact>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS + " WHERE "
				+ KEY_CONTACT_TYPE + " = " + type;
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Contact contact = new Contact(cursor.getString(0),
						cursor.getString(1), cursor.getString(2),
						cursor.getString(3), Integer.parseInt(cursor
								.getString(4)));
				// Adding contact to list
				contactList.add(contact);
			} while (cursor.moveToNext());
		}
		db.close();
		// return contact list
		return contactList;
	}

	// Getting contacts Count
	public int getContactsCount() {
		String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		cursor.close();

		// return count
		return cursor.getCount();
	}

	// Updating single contact
	public int updateContact(Contact contact) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_ID, contact.get_id());
		values.put(KEY_NAME, contact.get_name());
		values.put(KEY_PH_NO, contact.get_phone_number());
		values.put(KEY_CONTACT_ID, contact.get_contact_id());
		values.put(KEY_CONTACT_TYPE, contact.get_type());
		// updating row
		return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
				new String[] { String.valueOf(contact.get_id()) });
	}

	// Deleting single contact
	public void deleteContact(Contact contact) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_CONTACTS, KEY_CONTACT_ID + " = ?",
				new String[] { String.valueOf(contact.get_contact_id()) });
		db.close();
	}

	/**
	 * Xu ly message o day. Bao gom cac thao tac them moi, sua, xoa, cap nhat
	 * message
	 * 
	 * */

	/**
	 * Add new message
	 * 
	 * @param msg
	 */
	public void addMessage(Message msg) {
		SQLiteDatabase db = this.getWritableDatabase();

		// Log.d("FAILED",
		// "##########################Contact da duoc chen vao bang");
		ContentValues values = new ContentValues();
		values.put(MSG_KEY_TITLE, msg.get_title()); // Msg title
		values.put(MSG_KEY_CONTENT, msg.get_content()); // Msg content
		values.put(MSG_KEY_DEFAULT, msg.get_isDefault());// Msg set default

		db.insert(TABLE_MESSAGES, null, values);
		db.close(); // Closing database connection
	}

	/**
	 * Add new message
	 * 
	 * @param msg
	 * @return the row ID of the newly inserted row, or -1 if an error occurred
	 */
	public long insertMessage(Message msg) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(MSG_KEY_TITLE, msg.get_title()); // Msg title
		values.put(MSG_KEY_CONTENT, msg.get_content()); // Msg content
		values.put(MSG_KEY_DEFAULT, msg.get_isDefault());// Msg set default

		long id = db.insert(TABLE_MESSAGES, null, values);
		db.close(); // Closing database connection
		return id;
	}

	/**
	 * Get message by id
	 * 
	 * @param id
	 * @return the message by id
	 */
	public Message getMessageById(int id) {

		SQLiteDatabase db = this.getReadableDatabase();

		Cursor queryMsg = db.query(TABLE_MESSAGES, new String[] { MSG_KEY_ID,
				MSG_KEY_TITLE, MSG_KEY_CONTENT, MSG_KEY_DEFAULT }, MSG_KEY_ID
				+ "=?", new String[] { String.valueOf(id) }, null, null, null,
				String.valueOf(1));

		if (queryMsg != null)
			queryMsg.moveToFirst();
		db.close();
		return new Message(queryMsg.getInt(0), queryMsg.getString(1),
				queryMsg.getString(2), queryMsg.getInt(3));
	}

	/**
	 * Get message default
	 * 
	 * @return the message default
	 */
	public Message getMessageDefault() {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor queryMsg = db.query(TABLE_MESSAGES, new String[] { MSG_KEY_ID,
				MSG_KEY_TITLE, MSG_KEY_CONTENT, MSG_KEY_DEFAULT },
				MSG_KEY_DEFAULT + "=?", new String[] { String.valueOf(1) },
				null, null, null, String.valueOf(1));

		Message msg = null;

		if (queryMsg != null) {
			queryMsg.moveToFirst();

			msg = new Message(queryMsg.getInt(0), queryMsg.getString(1),
					queryMsg.getString(2), queryMsg.getInt(3));
			db.close();
		}

		if (msg == null) {

			msg = new Message();

			msg.set_title("Sms Default");
			msg.set_content("Im busy now. I will contact you as soon as possible. Thank you !");
			msg.set_id(1);
			msg.set_isDefault(1);
		}

		return msg;

	}

	/**
	 * set message default reply
	 * 
	 * @param msg
	 */
	public void setMessageDefault(Message msg) {
		updateMessage(msg);
	}

	/**
	 * Get all message
	 * 
	 * @return All row in table Message
	 */
	public List<Message> getAllMessage() {
		List<Message> messageList = new ArrayList<Message>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_MESSAGES + " ORDER BY "
				+ MSG_KEY_TITLE + " COLLATE NOCASE ASC";

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor queryMsg = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (queryMsg.moveToFirst()) {
			do {
				Message msg = new Message(queryMsg.getInt(0),
						queryMsg.getString(1), queryMsg.getString(2),
						queryMsg.getInt(3));
				// Adding message to list
				messageList.add(msg);
			} while (queryMsg.moveToNext());
		}
		db.close();
		// return message list
		return messageList;
	}

	/**
	 * Updating single message
	 * 
	 * @param msg
	 * @return the number of rows affected
	 */
	public int updateMessage(Message msg) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(MSG_KEY_ID, msg.get_id());
		values.put(MSG_KEY_TITLE, msg.get_title());
		values.put(MSG_KEY_CONTENT, msg.get_content());
		values.put(MSG_KEY_DEFAULT, msg.get_isDefault());

		// updating row
		int success = db.update(TABLE_MESSAGES, values, MSG_KEY_ID + " = ?",
				new String[] { String.valueOf(msg.get_id()) });

		db.close();
		return success;
	}

	/**
	 * Delete message
	 * 
	 * @param
	 * @return the Number of rows affected if a whereClause is passed in, 0
	 *         otherwise.
	 */
	public int deleteMessage(Message msg) {
		SQLiteDatabase db = this.getWritableDatabase();
		int success = db.delete(TABLE_MESSAGES, MSG_KEY_ID + " = ?",
				new String[] { String.valueOf(msg.get_id()) });
		db.close();

		return success;
	}

	public RowRecord getNameRecordDefault() {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor queryMsg = db.query(TABLE_RECORD, new String[] { RECORD_KEY,
				RECORD_NAME, RECORD_PATH }, RECORD_KEY + "=?",
				new String[] { "defaultrecord" }, null, null, null, "1");

		RowRecord rr = null;

		if (queryMsg != null) {
			queryMsg.moveToFirst();

			rr = new RowRecord(queryMsg.getString(1), queryMsg.getString(2));
		}

		db.close();

		return rr;
	}

	public int updateNameRecordDefault(String name, String path) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(RECORD_NAME, name);
		values.put(RECORD_PATH, path);
		// updating row
		int success = db.update(TABLE_RECORD, values, RECORD_KEY + " = ?",
				new String[] { "defaultrecord" });

		db.close();
		return success;
	}

	public long insertTimer(Timer timer) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(TIMER_NAME, timer.getNameTask());
		values.put(TIMER_DATE, timer.getDates());
		values.put(TIMER_TIME, timer.getTime());
		values.put(TIMER_REPEAT_WEEKLY, timer.getRepeat());
		values.put(TIMER_ISACTIVE, timer.getActive());
		long id = db.insert(TABLE_TIMER, null, values);
		db.close(); // Closing database connection
		return id;
	}

	public Timer getTimer(int id) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor queryTimer = db.query(TABLE_TIMER, new String[] { TIMER_NAME,
				TIMER_DATE, TIMER_TIME, TIMER_REPEAT_WEEKLY, TIMER_ISACTIVE },
				TIMER_ID + "=?", new String[] { String.valueOf(id) }, null,
				null, null, "1");

		Timer rr = null;

		if (queryTimer != null) {

			queryTimer.moveToFirst();

			rr = new Timer(id, queryTimer.getString(0),
					queryTimer.getString(1), queryTimer.getString(2),
					queryTimer.getInt(3), queryTimer.getInt(4));
		}

		db.close();

		return rr;
	}

	public int updateTimer(Timer timer) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(TIMER_NAME, timer.getNameTask());
		values.put(TIMER_DATE, timer.getDates());
		values.put(TIMER_TIME, timer.getTime());
		values.put(TIMER_REPEAT_WEEKLY, timer.getRepeat());
		values.put(TIMER_ISACTIVE, timer.getActive());
		// updating row
		int success = db.update(TABLE_TIMER, values, TIMER_ID + " = ?",
				new String[] { String.valueOf(timer.getId()) });

		db.close();
		return success;
	}

	public int deleteTimer(int id) {
		SQLiteDatabase db = this.getWritableDatabase();
		int success = db.delete(TABLE_TIMER, TIMER_ID + " = ?",
				new String[] { String.valueOf(id) });
		db.close();

		return success;
	}

	public List<Timer> getAllTimer() {
		List<Timer> timerList = new ArrayList<Timer>();
		// Select All Query

		String selectQuery = "SELECT  * FROM " + TABLE_TIMER + " ORDER BY "
				+ TIMER_NAME + " COLLATE NOCASE ASC";
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Timer timer = new Timer(cursor.getInt(0), cursor.getString(1),
						cursor.getString(2), cursor.getString(3),
						cursor.getInt(4), cursor.getInt(5));
				// Adding contact to list
				timerList.add(timer);
			} while (cursor.moveToNext());
		}
		db.close();
		// return contact list
		return timerList;
	}

	/**
	 * Func to check the time at phone call has exist on task
	 * */
	public boolean checkTimer() {
		Calendar cal = Calendar.getInstance();
		String day_of_week = "";
		switch (cal.get(Calendar.DAY_OF_WEEK)) {
		case 1:
			day_of_week = "Sun";
			break;
		case 2:
			day_of_week = "Mon";
			break;
		case 3:
			day_of_week = "Tue";
			break;
		case 4:
			day_of_week = "Wed";
			break;
		case 5:
			day_of_week = "Thu";
			break;
		case 6:
			day_of_week = "Fri";
			break;
		case 7:
			day_of_week = "Sat";
			break;
		default:
			break;
		}

		List<Timer> listTask = getAllTimer();

		for (Timer t : listTask) {
			if (t.getRepeat() >= 1) {
				String dates = t.getDates();

				int count = 0;

				if (dates.contains("Mon")) {
					count += 1;
				}

				if (dates.contains("Tue")) {
					count += 1;
				}

				if (dates.contains("Wed")) {
					count += 1;
				}

				if (dates.contains("Thu")) {
					count += 1;
				}

				if (dates.contains("Fri")) {
					count += 1;
				}

				if (dates.contains("Sat")) {
					count += 1;
				}

				if (dates.contains("Sun")) {
					count += 1;
				}

				t.setActive(count);

				updateTimer(t);
			}
		}

		SQLiteDatabase db = this.getReadableDatabase();
		String currentTimeString = String
				.valueOf(cal.get(Calendar.HOUR_OF_DAY))
				+ ":"
				+ String.valueOf(cal.get(Calendar.MINUTE));
		Log.d("TIMER", "Current time string =" + currentTimeString);
		Log.d("QUERY", "Day of week =" + day_of_week);
		String query = "SELECT * FROM " + TABLE_TIMER + " WHERE "
				+ TIMER_ISACTIVE + " >=1 AND " + TIMER_DATE + " LIKE '%"
				+ day_of_week + "%'";
		Log.d("STRING_QUERY", "String query =" + query);
		Cursor queryTimer = db.rawQuery(query, null);
		Log.d("COUNT", "Total result =" + queryTimer.getCount());
		if (queryTimer != null && queryTimer.getCount() > 0) {
			Log.d("QUERY", "Check query");

			if (queryTimer.moveToFirst()) {
				Log.d("QUERY", "Move to first !!!!!!!!!");
				do {

					Timer timerObj = new Timer(queryTimer.getInt(0),
							queryTimer.getString(1), queryTimer.getString(2),
							queryTimer.getString(3), queryTimer.getInt(4),
							queryTimer.getInt(5));

					String timer = queryTimer.getString(3);
					Log.d("TIMER", "Timer string =" + timer);
					String time[] = timer.split("__");
					Log.d("COUNT", "Tong so task =" + time.length);
					int i = 1;
					int numberTimer = time.length;
					for (String t : time) {
						Log.d("LOOP", "Lap lan thu =" + i);
						Log.d("TIMER", "t = " + t);
						String tim[] = t.trim().split(" - ");
						SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
						Calendar calendar = Calendar.getInstance();
						Date mDate1 = null;
						Date mDate2 = null;
						Date mDate = null;
						try {
							mDate1 = sdf.parse(tim[0].trim());
							mDate2 = sdf.parse(tim[1].trim());
							mDate = sdf.parse(currentTimeString.trim());
						} catch (java.text.ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						if (mDate1.before(mDate) && mDate2.after(mDate)) {
							db.close();
							return true;
						} else {
							if (mDate2.before(mDate)) {
								numberTimer -= 1;
							}

						}
						i++;
						if (numberTimer <= 0) {
							timerObj.setActive(timerObj.getActive() - 1);
							updateTimer(timerObj);
						}
					}
				} while (queryTimer.moveToNext());
			}
		} else {
			Log.d("QUERY",
					"Khong co task nao ngay hom nay, lam viec binh thuong nhe");
			db.close();
			return true;
		}
		db.close();
		return false;
	}
}